<template>
  <view class="product-list">
    <!-- 加载状态 -->
    <view v-if="loading && products.length === 0" class="loading-state">
      <wd-loading type="ring" size="32px" />
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 列表内容 -->
    <scroll-view
      v-else
      class="list-scroll"
      scroll-y
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="onLoadMore"
      :lower-threshold="100"
    >
      <!-- 物资卡片列表 -->
      <view class="product-cards">
        <view
          v-for="product in products"
          :key="product.id"
          class="product-card"
          @click="onProductClick(product)"
        >
          <!-- 左右布局容器 -->
          <view class="product-content">
            <!-- 左侧图片 -->
            <view class="product-image-wrapper">
              <image
                v-if="product.image"
                :src="product.image"
                class="product-image"
                mode="aspectFill"
                @error="handleImageError"
              />
              <view v-else class="no-image">
                <wd-icon name="image" size="24" color="#C7C7CC" />
                <text class="no-image-text">暂无图片</text>
              </view>

              <!-- 启用状态标识 -->
              <view class="status-badge" :class="{ 'status-badge--disabled': !product.enable }">
                <wd-icon
                  :name="product.enable ? 'check' : 'close'"
                  size="10"
                  color="white"
                  class="status-icon"
                />
                <text class="status-text">{{ product.enable ? '启用' : '禁用' }}</text>
              </view>
            </view>

            <!-- 右侧信息 -->
            <view class="product-info">
              <view class="info-header">
                <text class="product-name">{{ product.name || '未命名物资' }}</text>
                <text
                  v-if="product.productNumber"
                  class="product-number"
                  @click.stop="copyProductNumber(product.productNumber)"
                >
                  {{ product.productNumber }}
                </text>
              </view>

              <!-- 分类和仓库信息 -->
              <view class="info-meta">
                <view v-if="product.categoryName" class="meta-item">
                  <wd-icon name="folder" size="12" color="#8E8E93" />
                  <text class="meta-text">{{ product.categoryName }}</text>
                </view>
                <view v-if="product.warehouseName" class="meta-item">
                  <wd-icon name="location" size="12" color="#8E8E93" />
                  <text class="meta-text">{{ product.warehouseName }}</text>
                </view>
              </view>

              <!-- 规格信息摘要 -->
              <view
                v-if="product.productSkus && product.productSkus.length > 0"
                class="sku-summary"
              >
                <view class="sku-count">
                  <wd-icon name="grid" size="12" color="#007AFF" />
                  <text class="sku-text">{{ product.productSkus.length }}个规格</text>
                </view>
                <view class="total-stock">
                  <wd-icon name="package" size="12" color="#34C759" />
                  <text class="stock-text">库存 {{ getTotalStock(product.productSkus) }}</text>
                </view>
                <view
                  class="stock-status"
                  :class="getStockStatusClass(getTotalStock(product.productSkus))"
                >
                  <wd-icon
                    :name="getStockStatusIcon(getTotalStock(product.productSkus))"
                    size="12"
                    :color="getStockStatusColor(getTotalStock(product.productSkus))"
                  />
                  <text class="stock-status-text">
                    {{ getStockStatusText(getTotalStock(product.productSkus)) }}
                  </text>
                </view>
              </view>

              <!-- 操作按钮 -->
              <view class="action-buttons">
                <wd-button
                  size="small"
                  type="text"
                  @click.stop="onViewDetail(product)"
                  class="action-btn view-btn"
                >
                  <wd-icon name="eye" size="14" />
                  <text>详情</text>
                </wd-button>
                <wd-button
                  size="small"
                  type="text"
                  @click.stop="onEditProduct(product)"
                  class="action-btn edit-btn"
                >
                  <wd-icon name="edit" size="14" />
                  <text>编辑</text>
                </wd-button>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多状态 -->
      <view v-if="loadingMore" class="loading-more">
        <wd-loading type="ring" size="20px" />
        <text class="loading-text">加载更多...</text>
      </view>

      <!-- 没有更多数据 -->
      <view v-if="!hasMore && products.length > 0" class="no-more">
        <text class="no-more-text">没有更多数据了</text>
      </view>

      <!-- 空状态 -->
      <view v-if="!loading && products.length === 0" class="empty-state">
        <wd-icon name="package" size="64" color="#C7C7CC" class="empty-icon" />
        <text class="empty-title">暂无物资</text>
        <text class="empty-desc">当前筛选条件下没有找到物资</text>
        <wd-button type="primary" size="small" @click="onRefresh" class="retry-btn">
          重新加载
        </wd-button>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { getProductListApi } from '@/api/modules/rescue/product/product'
import type { IProduct } from '@/api/interface/rescue/product/product'

interface Props {
  /** 查询参数 */
  queryParams?: IProduct.Query
  /** 是否自动加载 */
  autoLoad?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  queryParams: () => ({}),
  autoLoad: true,
})

const emit = defineEmits<{
  'product-click': [product: IProduct.Row]
  'view-detail': [product: IProduct.Row]
  'edit-product': [product: IProduct.Row]
  refresh: []
  'load-more': []
}>()

// 响应式数据
const products = ref<IProduct.Row[]>([])
const loading = ref(false)
const refreshing = ref(false)
const loadingMore = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 计算属性
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

// 监听查询参数变化
watch(
  () => props.queryParams,
  () => {
    if (props.autoLoad) {
      refresh()
    }
  },
  { deep: true },
)

// 方法
const loadProducts = async (isRefresh = false, isLoadMore = false) => {
  if (isRefresh) {
    refreshing.value = true
    currentPage.value = 1
  } else if (isLoadMore) {
    loadingMore.value = true
    currentPage.value++
  } else {
    loading.value = true
    currentPage.value = 1
  }

  try {
    const params: IProduct.Query = {
      ...props.queryParams,
      page: currentPage.value,
      limit: pageSize.value,
    }

    const response = await getProductListApi(params)
    const newProducts = response.data?.rows || []

    if (isRefresh || !isLoadMore) {
      products.value = newProducts
    } else {
      products.value.push(...newProducts)
    }

    total.value = response.data?.total || 0
    hasMore.value = currentPage.value < totalPages.value

    // 触发事件
    if (isRefresh) {
      emit('refresh')
    } else if (isLoadMore) {
      emit('load-more')
    }
  } catch (error) {
    console.error('加载物资列表失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none',
    })

    // 如果是加载更多失败，需要回退页码
    if (isLoadMore) {
      currentPage.value--
    }
  } finally {
    loading.value = false
    refreshing.value = false
    loadingMore.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  loadProducts(true)
}

// 上拉加载更多
const onLoadMore = () => {
  if (!loadingMore.value && hasMore.value) {
    loadProducts(false, true)
  }
}

// 刷新列表
const refresh = () => {
  loadProducts(true)
}

// 事件处理
const onProductClick = (product: IProduct.Row) => {
  emit('product-click', product)
}

const onViewDetail = (product: IProduct.Row) => {
  emit('view-detail', product)
}

const onEditProduct = (product: IProduct.Row) => {
  emit('edit-product', product)
}

// 处理图片加载错误
const handleImageError = (e: any) => {
  console.warn('图片加载失败:', e)
}

// 获取标签样式
const getTagStyle = (tag: IProduct.TagInfo) => {
  if (!tag.backgroundColor && !tag.textColor) {
    return {
      backgroundColor: '#F2F2F7',
      color: '#8E8E93',
    }
  }

  if (tag.plain === 'true') {
    return {
      color: tag.backgroundColor || '#007AFF',
      borderColor: tag.backgroundColor || '#007AFF',
      backgroundColor: 'transparent',
      border: '1px solid',
    }
  } else {
    return {
      color: tag.textColor || '#FFFFFF',
      backgroundColor: tag.backgroundColor || '#007AFF',
    }
  }
}

// 计算总库存
const getTotalStock = (skus: IProduct.ProductSkuRow[]) => {
  return skus.reduce((total, sku) => total + (sku.stock || 0), 0)
}

// 获取库存状态类
const getStockStatusClass = (stock: number) => {
  if (stock <= 0) return 'out-of-stock'
  if (stock <= 10) return 'low-stock'
  return 'in-stock'
}

// 获取库存状态图标
const getStockStatusIcon = (stock: number) => {
  if (stock <= 0) return 'close'
  if (stock <= 10) return 'warning'
  return 'check'
}

// 获取库存状态颜色
const getStockStatusColor = (stock: number) => {
  if (stock <= 0) return '#FF3B30'
  if (stock <= 10) return '#FF9500'
  return '#34C759'
}

// 获取库存状态文本
const getStockStatusText = (stock: number) => {
  if (stock <= 0) return '缺货'
  if (stock <= 10) return '低库存'
  return '库存充足'
}

// 复制物资编号
const copyProductNumber = (productNumber: string) => {
  uni.setClipboardData({
    data: productNumber,
    success: () => {
      uni.showToast({
        title: '编号已复制',
        icon: 'success',
        duration: 1500,
      })
    },
    fail: () => {
      uni.showToast({
        title: '复制失败',
        icon: 'none',
        duration: 1500,
      })
    },
  })
}

// 初始加载
if (props.autoLoad) {
  loadProducts()
}

// 暴露方法
defineExpose({
  refresh,
  loadMore: onLoadMore,
})

defineOptions({
  name: 'ProductList',
})
</script>

<style lang="scss" scoped>
// Apple 设计系统变量
$system-blue: #007aff;
$system-green: #34c759;
$system-orange: #ff9500;
$system-red: #ff3b30;
$system-gray: #8e8e93;
$label-primary: #000000;
$label-secondary: rgba(60, 60, 67, 0.6);
$background-primary: #ffffff;
$background-secondary: #f2f2f7;
$separator: rgba(60, 60, 67, 0.36);

.product-list {
  height: 100%;
  background-color: $background-secondary;

  .loading-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 80px 20px;

    .loading-text {
      margin-top: 16px;
      font-size: 16px;
      color: $system-gray;
    }
  }

  .list-scroll {
    height: 100%;
  }

  .product-cards {
    padding: 16px;
    display: flex;
    flex-direction: column;
    gap: 16px;

    .product-card {
      background-color: $background-primary;
      border-radius: 16px;
      padding: 16px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
      border: 1px solid rgba(0, 0, 0, 0.06);
      transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
      overflow: hidden;
      position: relative;

      &:active {
        transform: scale(0.98);
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
      }

      &:hover {
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        transform: translateY(-2px);
      }

      // 添加左侧彩色条
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 4px;
        background: linear-gradient(135deg, $system-blue 0%, $system-green 100%);
        border-radius: 2px 0 0 2px;
      }

      .product-content {
        display: flex;
        gap: 12px;
        align-items: flex-start;
      }

      .product-image-wrapper {
        position: relative;
        width: 100px;
        height: 100px;
        flex-shrink: 0;
        border-radius: 12px;
        overflow: hidden;

        .product-image {
          width: 100%;
          height: 100%;
          border-radius: 12px;
          object-fit: cover;
        }

        .no-image {
          width: 100%;
          height: 100%;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          background-color: $background-secondary;
          border-radius: 12px;
          border: 2px dashed rgba(199, 199, 204, 0.5);
          gap: 4px;

          .no-image-text {
            font-size: 10px;
            color: #c7c7cc;
            font-weight: 500;
          }
        }

        .status-badge {
          position: absolute;
          top: 4px;
          right: 4px;
          padding: 2px 6px;
          border-radius: 8px;
          background-color: rgba(52, 199, 89, 0.9);
          backdrop-filter: blur(10px);
          display: flex;
          align-items: center;
          gap: 2px;

          .status-icon {
            flex-shrink: 0;
          }

          .status-text {
            font-size: 9px;
            color: white;
            font-weight: 600;
          }

          &--disabled {
            background-color: rgba(142, 142, 147, 0.9);
          }
        }
      }

      .product-info {
        flex: 1;
        min-width: 0;

        .info-header {
          margin-bottom: 8px;

          .product-name {
            display: block;
            font-size: 16px;
            font-weight: 600;
            color: $label-primary;
            line-height: 1.3;
            margin-bottom: 6px;
            // 文本省略处理
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .product-number {
            font-size: 11px;
            color: $system-blue;
            font-weight: 500;
            background-color: rgba(0, 122, 255, 0.1);
            padding: 3px 6px;
            border-radius: 8px;
            display: inline-block;
            border: 1px solid rgba(0, 122, 255, 0.2);
            cursor: pointer;
            transition: all 0.2s ease;

            &:active {
              background-color: rgba(0, 122, 255, 0.2);
              transform: scale(0.98);
            }
          }
        }

        .info-meta {
          display: flex;
          gap: 12px;
          margin-bottom: 8px;

          .meta-item {
            display: flex;
            align-items: center;
            gap: 3px;

            .meta-text {
              font-size: 12px;
              color: $label-secondary;
            }
          }
        }

        .sku-summary {
          display: flex;
          gap: 8px;
          margin-bottom: 8px;
          flex-wrap: wrap;

          .sku-count,
          .total-stock,
          .stock-status {
            display: flex;
            align-items: center;
            gap: 2px;

            .sku-text,
            .stock-text,
            .stock-status-text {
              font-size: 11px;
              font-weight: 500;
            }

            .sku-text {
              color: $system-blue;
            }

            .stock-text {
              color: $system-green;
            }
          }

          .stock-status {
            padding: 2px 4px;
            border-radius: 6px;
            background-color: rgba(52, 199, 89, 0.1);

            &.out-of-stock {
              background-color: rgba(255, 59, 48, 0.1);
              .stock-status-text {
                color: $system-red;
              }
            }

            &.low-stock {
              background-color: rgba(255, 149, 0, 0.1);
              .stock-status-text {
                color: $system-orange;
              }
            }

            &.in-stock {
              background-color: rgba(52, 199, 89, 0.1);
              .stock-status-text {
                color: $system-green;
              }
            }
          }
        }

        .action-buttons {
          display: flex;
          gap: 6px;
          padding-top: 8px;
          border-top: 1px solid rgba(0, 0, 0, 0.06);
          margin-top: 4px;

          .action-btn {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 3px;
            padding: 6px 8px;
            border-radius: 8px;
            transition: all 0.2s ease;
            font-weight: 500;
            min-height: 28px;
            font-size: 12px;

            &.view-btn {
              color: $system-blue;
              background-color: rgba(0, 122, 255, 0.1);
              border: 1px solid rgba(0, 122, 255, 0.2);

              &:active {
                background-color: rgba(0, 122, 255, 0.2);
                transform: scale(0.98);
              }
            }

            &.edit-btn {
              color: $system-orange;
              background-color: rgba(255, 149, 0, 0.1);
              border: 1px solid rgba(255, 149, 0, 0.2);

              &:active {
                background-color: rgba(255, 149, 0, 0.2);
                transform: scale(0.98);
              }
            }
          }
        }
      }
    }
  }

  .loading-more {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 20px;

    .loading-text {
      font-size: 14px;
      color: $system-gray;
    }
  }

  .no-more {
    text-align: center;
    padding: 20px;

    .no-more-text {
      font-size: 14px;
      color: $system-gray;
    }
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 80px 20px;

    .empty-icon {
      margin-bottom: 16px;
      opacity: 0.6;
    }

    .empty-title {
      font-size: 18px;
      font-weight: 600;
      color: $label-primary;
      margin-bottom: 8px;
    }

    .empty-desc {
      font-size: 15px;
      color: $label-secondary;
      text-align: center;
      line-height: 1.4;
      margin-bottom: 24px;
    }

    .retry-btn {
      padding: 8px 20px;
      border-radius: 20px;
    }
  }
}

// 响应式设计
@media (max-width: 375px) {
  .product-cards {
    padding: 12px;
    gap: 12px;

    .product-card {
      padding: 12px;

      .product-image-wrapper {
        height: 140px;
      }

      .product-info {
        .info-header {
          .product-name {
            font-size: 16px;
            -webkit-line-clamp: 1;
          }

          .product-number {
            font-size: 11px;
            padding: 3px 6px;
          }
        }

        .sku-summary {
          gap: 8px;

          .sku-count,
          .total-stock,
          .stock-status {
            .sku-text,
            .stock-text,
            .stock-status-text {
              font-size: 12px;
            }
          }
        }
      }

      .action-buttons {
        gap: 6px;

        .action-btn {
          padding: 8px 10px;
          min-height: 32px;
          font-size: 14px;
        }
      }
    }
  }
}

// 大屏幕优化
@media (min-width: 768px) {
  .product-cards {
    padding: 20px;
    gap: 20px;

    .product-card {
      padding: 20px;

      .product-image-wrapper {
        height: 180px;
      }

      .product-info {
        .info-header {
          .product-name {
            font-size: 18px;
          }
        }
      }
    }
  }
}
</style>
